package cn.com.common.job.task;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.com.common.constants.Constants;
import cn.com.gas.entity.GasStationDeptEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.entity.GasStationinfoForecastEntity;
import cn.com.gas.entity.GasStaytimeResultEntity;
import cn.com.gas.service.GasStationDeptService;
import cn.com.gas.service.GasStationinfoForecastService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.gas.service.GasStaytimeResultService;
import cn.com.system.entity.SysDept;
import cn.com.system.service.DeptService;
import cn.com.thirdparty.entity.VExJrjyXjNyQyCyEntity;
import cn.com.thirdparty.entity.VExJyzNyEntity;
import cn.com.thirdparty.service.VExJrjyXjNyQyCyService;
import cn.com.thirdparty.service.VExJyzNyService;
import cn.com.util.TsBqUtils;

/**
 * 定时任务(演示Demo，可删除) testTask为spring bean的名称， 方法名称必须是run
 *
 * @author wenbin
 * @version V1.0
 * @date 2020年3月18日
 */
@Component("gasVExJrjyNyHzProcessTask")
@DisallowConcurrentExecution
public class GasVExJrjyNyHzProcessTask {
	
	@Value("${gasstation.timedTask.gasVExJrjyNyHzProcessTask}")
	private String gasVExJrjyNyHzProcessTask;
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private VExJrjyXjNyQyCyService vExJrjyXjNyQyCyService;
	@Autowired
	private VExJyzNyService vExJyzNyService;
	
	@Autowired
	private DeptService deptService;
	@Autowired
	private GasStaytimeResultService gasStaytimeResultService;
	@Autowired
	private GasStationDeptService gasStationDeptService;
	@Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private GasStationinfoForecastService gasStationinfoForecastService;
	
	
	LocalDate now = LocalDate.now();
	LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
	LocalDate firstDayOfNextMonth = now.with(TemporalAdjusters.firstDayOfNextMonth());

	public void run(String params) throws Exception {
		logger.debug("gasVExJrjyNyHzProcessTask定时任务正在执行，参数为：{}", params);

		logger.debug("application参数为gasVExJrjyNyHzProcessTask：{}", gasVExJrjyNyHzProcessTask);

		if (gasVExJrjyNyHzProcessTask.equals(Constants.JOB_STOP)) {

			logger.debug("application配置文件控制不执行gasVExJrjyNyHzProcessTask定时任务");
			throw new Exception("application配置文件控制不执行gasVExJrjyNyHzProcessTask定时任务");
		
		}
		
		
		LocalDate currentDate = LocalDate.now();
				
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
		
		String formattedDate = currentDate.format(formatter);
		
		// 计算预估值
		// 获取当前的 YearMonth 对象
        YearMonth currentYearMonth = YearMonth.now();
        // 定义日期时间格式
        // 使用格式化器格式化当前的 YearMonth 对象
        String formattedYearMonth = currentYearMonth.format(DateTimeFormatter.ofPattern("yyyy-MM"));
		
		List<String> deptIdList = new ArrayList<>();
		List<String> pid = new ArrayList<>();
		
		List<GasStationDeptEntity> listGasStationDept = gasStationDeptService.list(Wrappers.lambdaQuery());
		if (TsBqUtils.isNotNull(listGasStationDept)) {
			for (GasStationDeptEntity gasStationDeptEntity : listGasStationDept) {
				pid.add(gasStationDeptEntity.getEndangerId());
				deptIdList.add(gasStationDeptEntity.getDeptId());
			}
		}

		List<String> _deptIdList = deptIdList.stream().distinct().collect(Collectors.toList());

		for (String taxorgcode : _deptIdList) {
			SysDept sysDept = deptService.getById(taxorgcode);
			if(TsBqUtils.isNotNull(sysDept)){
				
				BigDecimal qyJe = new BigDecimal(0);
				BigDecimal cyJe = new BigDecimal(0);
				
				BigDecimal styJe = new BigDecimal(0);
				BigDecimal dfyzJe = new BigDecimal(0);
				
				BigDecimal qyJeCs = new BigDecimal(0);
				BigDecimal cyJeCs = new BigDecimal(0);
				
				BigDecimal styJeCs = new BigDecimal(0);
				BigDecimal dfyzJeCs = new BigDecimal(0);
				
				LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();

				queryWrapper.in(GasStationinfoEntity::getPid, pid);
				queryWrapper.eq(GasStationinfoEntity::getType, "group");
				queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				queryWrapper.eq(GasStationinfoEntity::getTaxorgcode, taxorgcode);
				
				List<GasStationinfoEntity> gasStationinfoList = gasStationinfoService.list(queryWrapper);
				
				for (GasStationinfoEntity stationinfo : gasStationinfoList) {
					String id = stationinfo.getId();
					String name = stationinfo.getName();
					
					LambdaQueryWrapper<GasStaytimeResultEntity> queryWrapper1 = Wrappers.lambdaQuery();
					queryWrapper1.eq(GasStaytimeResultEntity::getStationId, id);
					// 当前月
					Date firstDayOfMonthDate = Date.from(firstDayOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
					Date firstDayOfNextMonthDate = Date.from(firstDayOfNextMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());

					queryWrapper1.ge(GasStaytimeResultEntity::getMessageDisappear, firstDayOfMonthDate);
					queryWrapper1.le(GasStaytimeResultEntity::getMessageDisappear, firstDayOfNextMonthDate);
					
					// queryWrapper1.ne(GasStaytimeResultEntity::getFromTopic,"/videocomm/status/aiemb/1qaz");

					
					List<GasStaytimeResultEntity> list = gasStaytimeResultService.list(queryWrapper1);
					
					BigDecimal jyzStyJe = new BigDecimal(0);
					BigDecimal jyzDfyzJe = new BigDecimal(0);
					BigDecimal jyzHzJe = new BigDecimal(0);
					
					BigDecimal jyzQyJe = new BigDecimal(0);
					BigDecimal jyzCyJe = new BigDecimal(0);
					
					
					for (GasStaytimeResultEntity staytimeResult : list) {
						String oils = staytimeResult.getOils();
						String price = staytimeResult.getPrice();
						
						if(oils.equals("汽油")){
							// 汽油
							jyzQyJe = jyzQyJe.add(new BigDecimal(price));
							qyJe = qyJe.add(new BigDecimal(price));
							
						}else{
							// 柴油
							jyzCyJe = jyzCyJe.add(new BigDecimal(price));
							cyJe = cyJe.add(new BigDecimal(price));
							
						}
						
						boolean contains = name.contains("中国");
						boolean contains1 = name.contains("中石油");
						boolean contains2 = name.contains("中石化");
						
						if (contains||contains1||contains2) {
							jyzStyJe = jyzStyJe.add(new BigDecimal(price));
							
							styJe = styJe.add(new BigDecimal(price));
						}else{
							jyzDfyzJe = jyzDfyzJe.add(new BigDecimal(price));
							
							dfyzJe = dfyzJe.add(new BigDecimal(price));
						}
						
						jyzHzJe = jyzHzJe.add(new BigDecimal(price));
						
					}
					
					
					VExJyzNyEntity vExJyzNy = new VExJyzNyEntity();
					
					vExJyzNy.setNy(formattedDate); // text 年月
					vExJyzNy.setSwjgDm(taxorgcode); // varchar 机关代码
					vExJyzNy.setSwjgMc(sysDept.getName()); // varchar 机关名称
					vExJyzNy.setJyzId(id); // varchar 加油站ID
					vExJyzNy.setJyzMc(name); // varchar 加油站名称
					vExJyzNy.setJyzJc(stationinfo.getShortname()); // varchar 加油站简称
					vExJyzNy.setXzqhDm(taxorgcode.substring(1,7)); // varchar 行政区划代码
					vExJyzNy.setXzqhMc(sysDept.getManagerName()); // varchar 行政区划名称
					
					double jyzHzJeNumber = Double.parseDouble(jyzHzJe.toString());
					double jyzDfyzJeNumber = Double.parseDouble(jyzDfyzJe.toString());
					double jyzStyJeNumber = Double.parseDouble(jyzStyJe.toString());
					
					double jyzQyJeNumber = Double.parseDouble(jyzQyJe.toString());
					double jyzCyJeNumber = Double.parseDouble(jyzCyJe.toString());
					
					vExJyzNy.setHzJe((int) Math.floor(jyzHzJeNumber)); // numeric 汇总金额
					
					vExJyzNy.setLc(list.size()); // numeric 辆次
					vExJyzNy.setStyJe((int) Math.floor(jyzStyJeNumber)); // numeric 三桶油金额
					vExJyzNy.setDfyzJe((int) Math.floor(jyzDfyzJeNumber)); // numeric 地方站金额
					
					vExJyzNy.setCyJe(jyzCyJeNumber);
					vExJyzNy.setQyJe(jyzQyJeNumber);
					
					
					// 获取预估值
					LambdaQueryWrapper<GasStationinfoForecastEntity> stationinfoForecastWrapper = Wrappers.lambdaQuery();

					stationinfoForecastWrapper.like(GasStationinfoForecastEntity::getTime, formattedYearMonth);
					stationinfoForecastWrapper.eq(GasStationinfoForecastEntity::getStationinfoId, id);
					List<GasStationinfoForecastEntity> forecastEntityList = gasStationinfoForecastService
							.list(stationinfoForecastWrapper);
					
					BigDecimal _styJeCs = new BigDecimal(0);
					BigDecimal _dfyzJeCs = new BigDecimal(0);
					BigDecimal _hzJeCs = new BigDecimal(0);
					
					if(TsBqUtils.isNotNull(forecastEntityList)){
						
						for (GasStationinfoForecastEntity entity : forecastEntityList) {
							String stationinfoId = entity.getStationinfoId();
							String forecastValue = entity.getForecastValue();
							BigDecimal forecastValueDecimal = new BigDecimal(forecastValue);
							
							GasStationinfoEntity stationinfoEntity = gasStationinfoService.getById(stationinfoId);
							String stationinfoName = stationinfoEntity.getName();
							
							String gasCoverage = stationinfoEntity.getGasCoverage();
							String gasLocation = stationinfoEntity.getGasLocation();
							
							if (TsBqUtils.isNotNull(gasCoverage) && TsBqUtils.isNotNull(gasLocation) && !"0".equals(gasCoverage)
									&& !"0".equals(gasLocation)) {

								BigDecimal coverageBigDecimal = new BigDecimal(gasCoverage);
								BigDecimal locationBigDecimal = new BigDecimal(gasLocation);

								BigDecimal divide = forecastValueDecimal.divide(coverageBigDecimal, 2,
										BigDecimal.ROUND_HALF_UP);

								forecastValueDecimal = divide.multiply(locationBigDecimal);

								int comparisonResult1 = coverageBigDecimal.compareTo(locationBigDecimal);
								
								if (comparisonResult1 == 0) {
									forecastValueDecimal = forecastValueDecimal.multiply(new BigDecimal("1.3"));

								} else {

									BigDecimal bigDecimal = coverageBigDecimal.divide(locationBigDecimal, 2,
											BigDecimal.ROUND_HALF_UP);

									int comparisonResult = bigDecimal.compareTo(new BigDecimal("0.5"));
									if (comparisonResult > 0) {
										// 大于 0.5
										forecastValueDecimal =  forecastValueDecimal.multiply(new BigDecimal("1.6"));
									} else if (comparisonResult < 0) {
										// 小于 0.5
										forecastValueDecimal =  forecastValueDecimal.multiply(new BigDecimal("2.3"));
									} else {
										// 等于 0.5
										forecastValueDecimal =  forecastValueDecimal.multiply(new BigDecimal("2"));
									}
								}
							} else {
								forecastValueDecimal = forecastValueDecimal.multiply(new BigDecimal("1.3"));
							}
							
							
							boolean contains = stationinfoName.contains("中国");
							boolean contains1 = stationinfoName.contains("中石油");
							boolean contains2 = stationinfoName.contains("中石化");
							
							_hzJeCs = _hzJeCs.add(forecastValueDecimal);
							if (contains||contains1||contains2) {
								// 三桶油
								_styJeCs = _styJeCs.add(forecastValueDecimal);
							}else{
								// 地方站
								_dfyzJeCs = _dfyzJeCs.add(forecastValueDecimal);
							}
						}
					}
					
					double _hzJeCsNumber = Double.parseDouble(_hzJeCs.toString());
					double _styJeCsNumber = Double.parseDouble(_styJeCs.toString());
					double _dfyzJeCsNumber = Double.parseDouble(_dfyzJeCs.toString());
					
					vExJyzNy.setHzJeCs((int) Math.floor(_hzJeCsNumber));
					
					vExJyzNy.setStyJeCs((int) Math.floor(_styJeCsNumber));
					vExJyzNy.setDfyzJeCs((int) Math.floor(_dfyzJeCsNumber));
					
					
					
					
					
					
					
					
					
					
					vExJyzNyService.saveVExJyzNy(vExJyzNy); // 写入 v_ex_jyz_ny 表
					
				}
				
				VExJrjyXjNyQyCyEntity vExJrjyXjNyQyCyEntity = new VExJrjyXjNyQyCyEntity();
				vExJrjyXjNyQyCyEntity.setNy(formattedDate);// ny 年月

				vExJrjyXjNyQyCyEntity.setSwjgDm(taxorgcode); // 税务机关代码
				vExJrjyXjNyQyCyEntity.setSwjgMc(sysDept.getName()); // 税务机关名称
				vExJrjyXjNyQyCyEntity.setXzqhDm(taxorgcode.substring(1,7)); // 行政区划代码
				vExJrjyXjNyQyCyEntity.setXzqhMc(sysDept.getManagerName());// 行政区划名称
				
				
				double qyJeNumber = Double.parseDouble(qyJe.toString());
				double cyJeNumber = Double.parseDouble(cyJe.toString());
				
				vExJrjyXjNyQyCyEntity.setQyJe((int) Math.floor(qyJeNumber)); //汽油-金额
				vExJrjyXjNyQyCyEntity.setCyJe((int) Math.floor(cyJeNumber)); //柴油-金额
				
				double dfyzJeNumber = Double.parseDouble(dfyzJe.toString());
				double styJeNumber = Double.parseDouble(styJe.toString());
				
				vExJrjyXjNyQyCyEntity.setDfyzJe((int) Math.floor(dfyzJeNumber)); //地方油站-金额
				vExJrjyXjNyQyCyEntity.setStyJe((int) Math.floor(styJeNumber)); //三桶油-金额
				
				LambdaQueryWrapper<GasStationinfoForecastEntity> stationinfoForecastWrapper = Wrappers.lambdaQuery();

				stationinfoForecastWrapper.like(GasStationinfoForecastEntity::getTime, formattedYearMonth);
				stationinfoForecastWrapper.eq(GasStationinfoForecastEntity::getTaxorgcode, taxorgcode);
				List<GasStationinfoForecastEntity> forecastEntityList = gasStationinfoForecastService
						.list(stationinfoForecastWrapper);
				
				if(TsBqUtils.isNotNull(forecastEntityList)){
					
					for (GasStationinfoForecastEntity entity : forecastEntityList) {
						String stationinfoId = entity.getStationinfoId();
						String forecastValue = entity.getForecastValue();
						BigDecimal forecastValueDecimal = new BigDecimal(forecastValue);
						
						GasStationinfoEntity stationinfoEntity = gasStationinfoService.getById(stationinfoId);
						String name = stationinfoEntity.getName();
						
						String gasCoverage = stationinfoEntity.getGasCoverage();
						String gasLocation = stationinfoEntity.getGasLocation();
						
						if (TsBqUtils.isNotNull(gasCoverage) && TsBqUtils.isNotNull(gasLocation) && !"0".equals(gasCoverage)
								&& !"0".equals(gasLocation)) {

							BigDecimal coverageBigDecimal = new BigDecimal(gasCoverage);
							BigDecimal locationBigDecimal = new BigDecimal(gasLocation);

							BigDecimal divide = forecastValueDecimal.divide(coverageBigDecimal, 2,
									BigDecimal.ROUND_HALF_UP);

							forecastValueDecimal = divide.multiply(locationBigDecimal);

							int comparisonResult1 = coverageBigDecimal.compareTo(locationBigDecimal);
							if (comparisonResult1 == 0) {
								forecastValueDecimal = forecastValueDecimal.multiply(new BigDecimal("1.3"));

							} else {

								BigDecimal bigDecimal = coverageBigDecimal.divide(locationBigDecimal, 2,
										BigDecimal.ROUND_HALF_UP);

								int comparisonResult = bigDecimal.compareTo(new BigDecimal("0.5"));
								if (comparisonResult > 0) {
									// 大于 0.5
									forecastValueDecimal = forecastValueDecimal.multiply(new BigDecimal("1.6"));
								} else if (comparisonResult < 0) {
									// 小于 0.5
									forecastValueDecimal = forecastValueDecimal.multiply(new BigDecimal("2.3"));
								} else {
									// 等于 0.5
									forecastValueDecimal = forecastValueDecimal.multiply(new BigDecimal("2"));
								}
							}
						} else {
							forecastValueDecimal = forecastValueDecimal.multiply(new BigDecimal("1.3"));
						}
						
						
						boolean contains = name.contains("中国");
						boolean contains1 = name.contains("中石油");
						boolean contains2 = name.contains("中石化");
						
						qyJeCs = qyJeCs.add(forecastValueDecimal);
						if (contains||contains1||contains2) {
							// 三桶油
							styJeCs = styJeCs.add(forecastValueDecimal);
						}else{
							// 地方站
							dfyzJeCs = dfyzJeCs.add(forecastValueDecimal);
						}
					}
				}
				
				double qyJeCsNumber = Double.parseDouble(qyJeCs.toString());
				double cyJeCsNumber = Double.parseDouble(cyJeCs.toString());
				
				vExJrjyXjNyQyCyEntity.setQyJeCs((int) Math.floor(qyJeCsNumber)); //汽油-金额
				vExJrjyXjNyQyCyEntity.setCyJeCs((int) Math.floor(cyJeCsNumber)); //柴油-金额
				
				double dfyzJeCsNumber = Double.parseDouble(dfyzJeCs.toString());
				double styJeCsNumber = Double.parseDouble(styJeCs.toString());
				
				vExJrjyXjNyQyCyEntity.setDfyzJeCs((int) Math.floor(dfyzJeCsNumber)); //地方油站-金额
				vExJrjyXjNyQyCyEntity.setStyJeCs((int) Math.floor(styJeCsNumber)); //三桶油-金额
				
				
				
				vExJrjyXjNyQyCyService.saveVExJrjyXjNyQyCy(vExJrjyXjNyQyCyEntity);  // 写入 v_ex_jrjy_xj_ny_qy_cy 表
			}
		}
	}
	
	public static void main(String[] args) {
		
	}
	
	
}
